package services

import (
	"errors"
	"hft/Database/admin"
	"hft/Http/Models/dao"
	"hft/Http/Models/request"
	utils "hft/Http/Utils"
	"hft/global"
	"hft/tools"
	"strconv"
	"strings"
)

type CommonTag struct{}

func (*CommonTag) CreateTag(claims tools.BaseClaims, tag *admin.CommonTag) (err error) {

	var account *admin.Account

	err = global.OC_DB.Scopes(dao.ParseAccountDao.Parse(claims, global.OC_DB)).First(&account).Error

	if err != nil {
		return errors.New("找不到该账号信息")
	}

	tag.AccountId = int(account.ID)
	tag.AccountLink = account.AccountLink
	// tag.AccountName = account.NickName

	var accountIds []int

	var strList = strings.Split(account.AccountLink, ",")

	strList = strList[1 : len(strList)-1]

	for _, v := range strList {
		var id, _ = strconv.Atoi(v)
		accountIds = append(accountIds, id)
	}

	err = global.OC_DB.Where("id IN ?", accountIds).FirstOrCreate(&tag).Error

	if err != nil {
		return errors.New("该标签已存在")
	}

	return nil
}

func (*CommonTag) EditTag(claims tools.BaseClaims, tag *admin.CommonTag) (err error) {
	var account *admin.Account
	var newTag *admin.CommonTag
	if tag.ID == 0 {
		return errors.New("无效的操作")
	}

	err = global.OC_DB.Scopes(dao.ParseAccountDao.Parse(claims, global.OC_DB)).First(&account).Error

	if err != nil {
		return errors.New("找不到该账号信息")
	}

	err = global.OC_DB.First(&newTag, tag.ID).Error

	if err != nil {
		return errors.New("没有该标签信息")
	}

	if newTag.AccountId != int(account.ID) {
		return errors.New("你无权修改该标签")
	}
	tag.AccountLink = account.AccountLink

	err = global.OC_DB.Model(&admin.CommonTag{}).Where("id = ?", tag.ID).Updates(map[string]interface{}{"name": tag.Name, "sort": tag.Sort}).Error

	if err != nil {
		return errors.New("该标签已存在")
	}

	return nil
}

func (*CommonTag) GetTagList(claims tools.BaseClaims, paginate *request.CommonTagSearch) (list *utils.Page, err error) {

	var account *admin.Account

	var tags []*admin.CommonTag

	err = global.OC_DB.Scopes(dao.ParseAccountDao.Parse(claims, global.OC_DB)).First(&account).Error

	if err != nil {
		return nil, errors.New("找不到该账号信息")
	}

	var accountIds []int

	var strList = strings.Split(account.AccountLink, ",")

	strList = strList[1 : len(strList)-1]

	for _, v := range strList {
		var id, _ = strconv.Atoi(v)
		accountIds = append(accountIds, id)
	}

	err = global.OC_DB.Scopes(dao.GetTagDao.GetTagList(accountIds, paginate, global.OC_DB)).Find(&tags).Limit(-1).Offset(-1).Count(&paginate.Total).Error

	if err != nil {
		return nil, errors.New("未知错误")
	}

	paginate.Page.Data = tags

	return &paginate.Page, nil
}

var TagServices = new(CommonTag)
